<template>
  <div class="home">
    <!-- bg-img -->
    <Bg></Bg>
    <!-- form -->
    <van-form
      class="form"
      @submit="onSubmit"
    >
      <div class="list">
        <van-field
          ref="user"
          v-model="realName"
          class="user"
          clearable
          center
          label-width="4em"
          label-align="right"
          label-class="label"
          label="姓名"
          input-align="left"
          :rules="userRules"
          placeholder="请输入姓名"
        ></van-field>
        <span class="line"></span>
      </div>
      <div class="list list1">
        <van-field
          ref="idCard"
          v-model="idCard"
          class="user"
          clearable
          center
          label-width="4em"
          label-align="right"
          input-align="left"
          label-class="label"
          label="身份证号"
          :rules="idRules"
          placeholder="请输入身份证号"
        />
        <span class="line"></span>
      </div>
      <div class="list list2">
        <van-field
          ref="mobile"
          v-model="mobile"
          class="tel"
          clearable
          center
          label-width="4em"
          label-align="right"
          label-class="label"
          label="手机号"
          :rules="telRules"
          placeholder="请输入国内手机号"
        />
        <span class="line"></span>
      </div>
      <!-- 添加验证码 -->
      <div class="list list3">
        <van-field
          v-model="captcha"
          class="code"
          center
          label-width="4em"
          label-align="right"
          label-class="label"
          label="验证码"
          placeholder="请输入验证码"
          :rules="captchaRules"
        />
        <div
          class="img"
          @click="fnrefresh"
        >
          <img
            :src="src"
            alt=""
          >
        </div>
        <span class="line"></span>
        <span class="txt">点击图片刷新验证码</span>
      </div>
      <!--  -->
      <div class="list list4">
        <van-field
          v-model="code"
          class="code"
          center
          label-width="4em"
          label-align="right"
          label-class="label"
          label="动态码"
          placeholder="请输入动态码"
          :rules="codeRules"
          @focus="focusfn"
        />
        <van-button
          v-show="shows"
          class="sendCode"
          type="default"
          @click="sendCode"
        >发送动态码</van-button>
        <!-- <span
          v-show="shows"
          class="sendCode"
          @click="sendCode"
        >发送动态码</span> -->
        <span
          v-show="!shows"
          class="sendCode1"
        >{{ count }}秒</span>
        <span class="line"></span>
      </div>
      <!--  -->
      <div class="btn">
        <van-button
          class="btn_sub"
          color="#2683FA"
          text="立即注册"
          size="large"
          block
          :disabled="disabled"
          @click="onSubmit"
        >立即注册</van-button>
      </div>
    </van-form>
    <!-- <van-loading type="spinner" vertical :class="center" color="#0094ff" size="50px"> 加载中……</van-loading> -->
    <!-- foot -->
    <div class="foot">
      <div>注册若出现问题，可联系客服热线</div>
      <div
        class="telephone"
        @click="telfn(4006782050)"
      >400-678-2050</div>
    </div>
    <!-- 弹窗提示 -->

    <!-- 遮罩层 -->
    <van-overlay
      class="overlay"
      :show="show"
      @click="show = false"
    >
      <div
        class="wrapper"
        @click.stop
      >
        <van-loading
          type="spinner"
          vertical
          :class="center"
          color="#0094ff"
          size="50px"
        />
      </div>
    </van-overlay>
  </div>
</template>

<script>
// @ is an alias to /src
import { Form, Field, Button, Loading, Overlay, Dialog } from 'vant'
import Bg from '@/components/Bg.vue'
// import src from '@/assets/2977/26@2x.png'
// console.log(src)
// import { throttle } from 'throttle-debounce'
import debounce from '@/utils/debounce' // 防抖函数
import getQuery from '@/utils/getQuery'
import instance from '@/request/index'
import 'vant/lib/index.css'
import IdentityCodeValid from '@/utils/identityCodeValid' // 身份证验证
import mobile from '@/utils/mobile' // 手机验证
import deviceInfo from '@/utils/index' // 设备
// console.log(IdentityCodeValid('411524198712045154'))
// import { Field } from 'vant'
export default {
  name: 'Home',
  components: {
    VanForm: Form,
    VanField: Field,
    VanButton: Button,
    VanLoading: Loading,
    VanOverlay: Overlay,
    // VanDialog: Dialog,
    Bg
  },
  data() {
    return {
      uuid: null, // 验证码返回的字段
      device: null,
      captcha: null, // 用户注册需要的验证码字段
      imgsrc: require('@/assets/2977/26@2x.png'),
      src: '',
      fnSendCode: null, // 存放防抖封装后的验证码函数
      fnSendRegister: null, // 存放防抖封装后的注册函数
      shows: true, // 发送验证码显示
      count: '', // 倒计时数字
      timer: null, // 倒计时
      unique: true, // 防止重复弹出
      show: false, // 遮罩层
      center: 'center',
      display: '',
      realName: '',
      idCard: '',
      mobile: '',
      code: '',
      orgId: '',
      isCode: false,
      disabled: true,
      userRules: [
        {
          // required: true,
          message: async () => {
            console.log(this.unique + '用户.......')
            if (this.unique) {
              this.unique = false // 后面的空白不会重复弹出
              await Dialog({ message: '请填写姓名' }).then(() => {
                console.log(this.$refs)
                this.$nextTick(() => {
                  this.$refs.user.focus()
                  this.unique = true
                })
              })
            }
          },
          trigger: 'onBlur'
        },
        {
          validator: async (value) => {
            // console.log(this.$refs.user)
            // return /^[\u2E80-\u9FFF]+$/.test(value)
            if (value === '') return
            if (this.unique) {
              this.unique = false
              if (/^[\u2E80-\u9FFF]+$/.test(value)) {
                this.unique = true
                return true
              }
              // console.log(await Dialog({ message: '姓名格式不对' }))
              await Dialog({ message: '请填写姓名' }).then(() => {
                console.log(this.$refs)
                this.$refs.user.focus()
                this.unique = true
              })
              return false
            }
          }
        }
      ],
      idRules: [
        {
          // required: true,
          message: async () => {
            console.log(this.unique + '身份证.......')
            if (this.unique) {
              this.unique = false
              await Dialog({ message: '请填写身份证号' }).then(() => {
                console.log(this.$refs)
                this.$nextTick(() => {
                  this.$refs.idCard.focus()
                  this.unique = true
                })
              })
            }
          },
          trigger: 'onBlur'
        },
        {
          validator: async (value) => {
            if (value === '') return
            if (this.unique) {
              this.unique = false
              if (IdentityCodeValid(value)) {
                this.unique = true
                return IdentityCodeValid(value)
              }
              await Dialog({
                message: '您输入的身份证号错误，请重新输入'
              }).then(() => {
                console.log(this.$refs)
                this.$refs.idCard.focus()
                this.unique = true
              })
              return false
            }
          }
        }
      ],
      telRules: [
        {
          // required: true,
          message: async () => {
            if (this.unique) {
              this.unique = false
              await Dialog({ message: '请填写手机号' }).then(() => {
                this.$refs.mobile.focus()
                this.unique = true
              })
            }
          },
          trigger: 'onBlur'
        },
        {
          validator: async (value) => {
            console.log(value)
            if (value === '') return
            if (this.unique) {
              this.unique = false
              if (mobile(value)) {
                this.unique = true
                return true
              }
              await Dialog({ message: '您输入的手机号错误' }).then(() => {
                this.$refs.mobile.focus()
                this.unique = true
              })
            }
            return false
          }
        }
      ],
      codeRules: [
        {
          // required: this.isCode,
          message: () => {
            return Dialog({ message: '请填写验证码' })
          }
        }
      ],
      captchaRules: [
        {
          // required: this.isCode,
          message: () => {
            return Dialog({ message: '请填写动态码' })
          }
        }
      ]
    }
  },
  created() {
    // 对验证码和注册防抖封装
    this.fnSendCode = debounce(this.sendCodeFn, 1000)
    this.fnSendRegister = debounce(this.registerFn, 1000)
    this.fnrefresh() // 刷新图片验证码
    this.device = deviceInfo() // 获取设备类型
    this.orgId = getQuery('orgId')
    // console.log(this.orgId)
  },
  methods: {
    // 刷新验证码
    fnrefresh() {
      console.log('-----')
      instance({
        method: 'get',
        url: '/api/uaa/v1/oauth/captchaImage' // 验证码接口
      })
        .then((res) => {
          this.src = 'data:image/jpeg;base64,' + res.data.data.img
          this.uuid = res.data.data.uuid
        })
        .catch(() => {
          console.log('刷新失败')
        })
    },
    focusfn() {
      // 聚焦事件
      console.log('====')
      this.disabled = false
    },
    telfn(num) {
      window.location.href = 'tel://' + num
    },
    getCount() {
      // 倒数计时器
      const TIME_COUNT = 60
      if (!this.timer) {
        this.count = TIME_COUNT
        this.shows = false
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--
          } else {
            this.shows = true
            clearInterval(this.timer)
            this.timer = null
          }
        }, 1000)
      }
    },
    blurFn() {
      // 改变按钮的禁用状态
      console.log('======')
      if (this.code === '') {
        this.disabled = true
      } else {
        this.disabled = false
      }
    },
    onSubmit(m) {
      // 注册之后提交触发的函数
      console.log('====')
      if (
        this.realName &&
        this.idCard &&
        this.mobile &&
        this.code &&
        this.captcha
      ) {
        this.show = true // 开启遮罩层
        this.fnSendRegister()
      } else if (this.realName === '') {
        // this.show = true
        Dialog({ message: '请填写姓名' })
      } else if (this.idCard === '') {
        // this.show = true
        Dialog({ message: '请填写身份证号' })
      } else if (this.mobile === '') {
        // this.show = true
        Dialog({ message: '请填写手机号' })
      } else if (this.captcha === '') {
        // this.show = true
        Dialog({ message: '请填写图片验证码' })
      } else if (this.code === '') {
        // this.show = true
        Dialog({ message: '请填写动态码' })
      }
      // console.log(this.userRules[1].validator(this.realName))
      // console.log(this.idRules[1].validator(this.idCard))
      // console.log(this.telRules[1].validator(this.mobile))
      // if (this.code === '') return Dialog({ message: '请输入验证码' })
      // if (this.userRules[1].validator(this.realName) === false) {
      //   return Dialog({ message: '姓名格式不对' })
      // }
      // if (this.userRules[1].validator(this.idCard) === false) {
      //   return Dialog({ message: '身份证格式不对' })
      // }
      // if (this.userRules[1].validator(this.mobile) === false) {
      //   return Dialog({ message: '手机格式不对' })
      // }
      // this.show = true
      // this.isCode = !this.isCode
      // this.$router.push({ name: 'Success' })
      // this.debounce()
      // this.$router.push({ name: 'Success' })
    },
    sendCode() {
      // 发送验证码
      if (this.realName === '') {
        // this.show = true
        Dialog({ message: '请填写姓名' })
      } else if (this.idCard === '') {
        // this.show = true
        Dialog({ message: '请填写身份证号' })
      } else if (this.mobile === '') {
        // this.show = true
        Dialog({ message: '请填写手机号' })
      } else if (this.captcha === '') {
        // this.show = true
        Dialog({ message: '请填写图片验证码' })
      } else {
        console.log('456')
        this.disabled = false
        this.getCount() // 开启倒计时
        this.fnSendCode() // 发送验证码请求
      }
      // if (this.mobile) {
      //   // Dialog({ message: '信息已填完' })
      //   console.log(this.shows)
      //   this.disabled = false
      //   this.getCount() // 开启倒计时
      //   this.fnSendCode() // 发送验证码请求
      // } else {
      //   Dialog({ message: '请填写手机号' })
      // }
    },
    registerFn() {
      // ajax 请求注册接口
      // 注册请求函数
      instance({
        method: 'post',
        url: '/api/oss/customer/v1/registration/registration', // 注册接口
        data: {
          code: this.code,
          idCard: this.idCard,
          mobile: this.mobile,
          orgId: this.orgId, // 隐形字段
          realName: this.realName,
          captcha: this.captcha, // 图片验证码字段
          uuid: this.uuid
        }
      }).then((res) => {
        console.log(res)
        this.show = false
        if (res.data.code === '10000') {
          this.$router.push({ name: 'Success' })
        } else {
          Dialog({ message: res.data.message })
          this.shows = true
          clearInterval(this.timer)
          this.timer = null
          return
        }
        // Dialog({ message: res.data.message }).then(() => {
        //   if (res.data.code === '10000') {
        //     this.$router.push({ name: 'Success' })
        //   }
        // })
        // this.$router.push({ name: 'Success' })
      })
    },
    sendCodeFn() {
      // ajax 请求验证码接口
      // 发送验证码请求
      console.log(111111 + '防抖')
      instance({
        method: 'post',
        url: '/api/oss/customer/v1/registration/sendSms', // 验证码接口
        data: {
          code: '',
          idCard: this.idCard,
          mobile: this.mobile,
          orgId: '1122', // 隐形字段
          realName: this.realName,
          uuid: this.uuid,
          captcha: this.captcha
        }
      })
        .then((res) => {
          console.log(res)
          if (res.data.code === '10001') {
            // 已经是会员，直接去下载 app 页面
            Dialog({
              message: res.data.message
            }).then(() => {
              if (this.device.iPhone) {
                location.href =
                  'https://apps.apple.com/cn/app/eCASC/id1474034891'
              } else if (this.device.android) {
                console.log('安卓')
                location.href =
                  'https://sj.qq.com/myapp/detail.htm?apkName=com.ctripcorp.htkjtrip'
              }
            })
          } else if (res.data.code === '10000') {
            // Dialog({
            //   message: '验证码成功'
            // })
            return
          } else {
            Dialog({
              message: res.data.message
            }).then(() => {
              this.fnrefresh()
              this.shows = true
              clearInterval(this.timer)
              this.timer = null
              return
            })
          }
          // 是会员
          // console.log('跳转')
          // Dialog({
          //   message: res.data.message
          // }).then(() => {
          //   console.log('chenggong')
          //   if (this.device.iPhone) {
          //     location.href = 'https://apps.apple.com/cn/app/eCASC/id1474034891'
          //   } else if (this.device.android) {
          //     console.log('安卓')
          //     location.href =
          //       'https://sj.qq.com/myapp/detail.htm?apkName=com.ctripcorp.htkjtrip'
          //   }
          // })
        })
        .catch(() => {
          Dialog({ message: '系统繁忙,请重新发送' }).then(() => {
            console.log('xitong出错')
            this.shows = true
            clearInterval(this.timer)
            this.timer = null
            return
          })
        })
    }
  }
}
</script>
<style lang="scss" scoped>
/* form */
.form {
  width: 702px;
  height: 770px;
  background: #ffffff;
  position: absolute;
  z-index: 1999;
  left: 24px;
  top: 372px;
  border-radius: 10px;
  /* border: 1px solid red; */
  .list {
    position: absolute;
    width: 622px;
    height: 80px;
    left: 42px;
    top: 64px;
    border: 2px solid #e5e5e5;
    border-radius:4px;
    font-size: 30px;
  }
}
.form .van-field__control {
  padding-left: 6px;
}
.form .user {
  font-size: 26px;
  padding-top: 20px;
  padding-left: 30px;
  height: 80px;
  box-sizing: border-box;
  color: red;
  // font-family: 'Source Han Sans CN';
  // border: 2px solid #e5e5e5;
}
.form .user::after {
  border-bottom: none;
}
.form .id {
  font-size: 30px;
  padding-top: 20px;
  height: 80px;
  padding-left: 30px;
}
.form .tel {
  font-size: 26px;
  padding-top: 20px;
  height: 80px;
  padding-left: 30px;
}
.form .code {
  font-size: 26px;
  padding-top: 20px;
  height: 80px;
  padding-left: 30px;
}
.form .sendCode {
  width: 204px;
  height: 40px;
  // border: 1px solid red;
  border: none;
  display: inline-block;
  color: #2683fa;
  // font-family: 'Source Han Sans CN';
  font-size: 26px;
  font-weight: 400;
  line-height: 32px;
  text-align: left;
  position: absolute;
  left: 416px;
  top: 22px;
  // border: 1px solid red;
}
.form .sendCode1 {
  display: inline-block;
  color: #2683fa;
  // font-family: 'Source Han Sans CN';
  font-size: 30px;
  font-weight: 400;
  line-height: 32px;
  text-align: left;
  position: absolute;
  left: 518px;
  top: 26px;
  padding: 0;
  // border: 1px solid red;
}
.form .label {
  color: red;
  // width: 200px;
  // bottom: 1px solid red;
}
.form .line {
  width: 2px;
  height: 36px;
  border-left: 1px solid #c1c1c1;
  box-sizing: content-box;
  position: absolute;
  left: 148px;
  top: 24px;
}
.form .list1 {
  top: 172px;
}
.form .list2 {
  top: 280px;
}
.form .list3 {
  top: 386px;
  .img {
    width: 148px;
    height: 64px;
    // border: 1px solid red;
    position: absolute;
    bottom: 8px;
    right: 20px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .txt {
    font-size: 24px;
    float: right;
    margin: 20px 0 0 0;
    color: #999999;
  }
}
.form .list4 {
  top: 530px;
}
@media screen and (min-width: 750px) {
  .form .line {
    top: 24px;
    left: 150px;
  }
  .form .sendCode {
    top: 18px;
    padding: 0;
  }
}
.form .btn {
  width: 622px;
  height: 80px;
  position: absolute;
  left: 42px;
  top: 666px;
}
.form .btn_sub {
  height: 80px;
  font-size: 30px;
}
/* foot */
.foot {
  width: 360px;
  height: 78px;
  position: absolute;
  left: 190px;
  top: 1180px;
  font-size: 22px;
  font-weight: 400;
  line-height: 50px;
  color: #999999;
  text-align: center;
}
.foot .telephone {
  color: #2683fa;
  // font-family: 'Source Han Sans CN';
  font-weight: 400;
}
.center {
  position: absolute;
  z-index: 9999;
  left: 44%;
  top: 50%;
}
.overlay {
  position: absolute;
  z-index: 19999;
}
</style>
